package org.skyeye.modeling.util;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.CommonNavigator;

public class WorkspaceUtil {

	public static IProject getCurrentProject() {
		IProject project = null;
		IResource resource = getSelectResource();
		if(resource != null) {
			project = resource.getProject();
		}
		return project;
	}
	
	public static IResource getSelectResource() {
		String explorerId = "org.eclipse.ui.navigator.ProjectExplorer";
		IResource resource = getSelectResource(explorerId);
		if(resource == null) {
			explorerId = "org.eclipse.jdt.ui.PackageExplorer";
			resource = getSelectResource(explorerId);
		}
		return resource;
	}
	
	public static IResource getSelectResource(String explorerId) {
		IResource resource = null;
		IViewPart viewPart = getSkyeyeViewPart(explorerId);
		if(viewPart instanceof CommonNavigator) {
			StructuredSelection selection = (StructuredSelection) ((CommonNavigator) viewPart).getCommonViewer().getSelection();
			if(selection != null) {
				Object element = selection.getFirstElement();
				if(element instanceof IResource) {
					resource = (IResource) element;
				}
			}
		}
		return resource;
	}

	public  static IViewPart getSkyeyeViewPart(String explorerId) {
		IWorkbenchPage workbenchPage = getWorkbenchPage();
		if(workbenchPage ==null)
			return null;
		IViewPart viewPart = workbenchPage.findView(explorerId);
		return viewPart;
	}
	
	public static IWorkbenchPage getWorkbenchPage() {
		IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if(activeWorkbenchWindow == null)
			return null;
		return activeWorkbenchWindow.getActivePage();
	}
	
	
	
}
